 
package com.zdkj.subway.stm.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zdkj.common.security.util.SecurityUtils;
import com.zdkj.subway.stm.dto.out.SwStStockDTO;
import com.zdkj.subway.stm.entity.SwStStock;
import com.zdkj.subway.stm.mapper.SwStStockMapper;
import com.zdkj.subway.stm.service.SwStStockService;
import com.zdkj.subway.stm.util.DateUtilStm;
import com.zdkj.subway.stm.util.JdbcUtil;
import com.zdkj.subway.stm.util.LocalDateConverter;
import com.zdkj.subway.stm.util.LocalDateTimeConverter;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 
 *
 * @author songtuo
 * @date 2020-07-14 11:52:58
 */
@Service
@AllArgsConstructor
@Slf4j
public class SwStStockServiceImpl extends ServiceImpl<SwStStockMapper, SwStStock> implements SwStStockService {

    private final SwStStockMapper swStStockMapper;

	private static final Logger LOGGER = LoggerFactory.getLogger(SwStStockServiceImpl.class);
    @Override
    public List<SwStStockDTO> calcData(String dateString) {
        return swStStockMapper.calcData(dateString);
    }

    @SneakyThrows
    @Override
    public boolean generateReport(SwStStock swStStockReq, Collection<SwStStock> collection) {
         //LOGGER.info("进入生成过程");
		List<SwStStock> list = new ArrayList<>();       
        //如果是单程票从接口表取 AGM回收、票房售出、TVM售出
        //单程票时取AGM回收
        Date statisticsDate = swStStockReq.getStatisticsDate();
        SimpleDateFormat dff = new SimpleDateFormat("yyyy-MM-dd");
        String format = dff.format(statisticsDate);
        int agmRecovery = 0;
        int tvmSellOut = 0;
        int boxOfficeSale = 0;
        int internetSales = 0;
        SimpleDateFormat dff2 = new SimpleDateFormat("yyyyMMdd");
        String statisticsDateStr = dff2.format(swStStockReq.getStatisticsDate());
        List<Map<String, Object>> maps1 = JdbcUtil.exeSqlQuery("select sum(ifnull(outCount,0)) as AGM_RECOVERY from sc_out_statistics where bookdate='" + statisticsDateStr + "'  and lineid= " + swStStockReq.getLineCode() + " and station_number= " + swStStockReq.getStationCode() + " and (producttype='1' or producttype='2' or producttype='3' or producttype='12')");
        if(null != maps1 && 0 != maps1.size() && null != maps1.get(0).get("AGM_RECOVERY")){          
            agmRecovery = Integer.valueOf(String.valueOf(maps1.get(0).get("AGM_RECOVERY")));
        }
        //单程票时取TVM售出
        List<Map<String, Object>> maps2 = JdbcUtil.exeSqlQuery("select sum(ifnull(sale_carnum,0)) as TVM_SELL_OUT from sc_fare_statistics where bookdate='" + statisticsDateStr + "' and lineid= " + swStStockReq.getLineCode() + " and station_number= " + swStStockReq.getStationCode() + " and producttype=3 and equipmenttype=1");
        if(null != maps2 && 0 != maps2.size() && null != maps2.get(0).get("TVM_SELL_OUT")){          
            tvmSellOut = Integer.valueOf(String.valueOf(maps2.get(0).get("TVM_SELL_OUT")));
        }
        //单程票时取票房售出
        List<Map<String, Object>> maps3 = JdbcUtil.exeSqlQuery("select sum(ifnull(sale_carnum,0)) as BOX_OFFICE_SALE from sc_fare_statistics where bookdate='" + statisticsDateStr + "' and lineid= " + swStStockReq.getLineCode() + " and station_number= " + swStStockReq.getStationCode() + " and (producttype=1 or producttype=3 or producttype=12) and equipmenttype=2");
        if(null != maps3 && 0 != maps3.size() && null != maps3.get(0).get("BOX_OFFICE_SALE")){           
            boxOfficeSale = Integer.valueOf(String.valueOf(maps3.get(0).get("BOX_OFFICE_SALE")));
        }
        //如果是单程票从互联网售票机取网络售出
        List<Map<String, Object>> maps = JdbcUtil.exeSqlQuery("SELECT SUM(IFNULL(sale_number,0)) AS INTERNET_SALES  from sw_st_internet_ticket_equipment_details WHERE DEL_FLAG = 0 and LINE_CODE='" + swStStockReq.getLineCode() + "' AND STATION_CODE='" + swStStockReq.getStationCode() + "' AND revenue_date='" + format + "'");
        if(null != maps && 0 != maps.size() && null != maps.get(0).get("INTERNET_SALES")){           
            internetSales = Integer.valueOf(String.valueOf(maps.get(0).get("INTERNET_SALES")));
        }
        //如果是单程票，从库存盘点获取BOM废票，TVM废票、AGM废票、网络机废票以及废票小计  20230412
		//-- 5: TVM废票   6：BOM废票   7：AGM废票  8：网络机废票
        
		int tvmScrap = 0;
		int bomScrap = 0;
		int agmScrap = 0;
		int netScrap = 0;

		List<Map<String, Object>> mapsCheck = getCheckScrapTicket(swStStockReq.getLineCode(),swStStockReq.getStationCode(),statisticsDateStr);
		 if(null != mapsCheck && 0 != mapsCheck.size()){ 
			 //System.out.println("库存盘点查询结果===="+mapsCheck.size());
			 for(int i=0;i<mapsCheck.size();i++){
			   Map<String, Object> map = mapsCheck.get(i);
			   String ticketType = String.valueOf(map.get("TICKET_TYPE"));
			   int checkNumber = Integer.valueOf(String.valueOf(map.get("CHECK_NUMBER")));
			   if("5".equals(ticketType)){
			      tvmScrap = checkNumber;
			   }else if("6".equals(ticketType)){
			      bomScrap = checkNumber;
			   }else if("7".equals(ticketType)){
			      agmScrap = checkNumber;
			   }else if("8".equals(ticketType)){
			      netScrap = checkNumber;
			   }			 
			}
		     //LOGGER.info("库存盘点查询结果=tvmScrap==="+tvmScrap+","+bomScrap+","+agmScrap+","+netScrap);
        }



        //配票
        String sqlTicket = " SELECT sum(a.WINDOWS_NUM-a.WINDOWS_CLOSE_NUM-a.INVALID_TICKET_NUM) num ,a.TICKET_NAME as ticketName,a.TICKET_TYPE as ticketType "+
                " from sw_st_ticket_petty_add_details  a,sw_st_ticket_petty_add b "+
                " where a.relation_id=b.id "+
                " and a.del_flag='0' "+
                " and b.del_flag='0' "+
                " and a.type='2' "+
                " and b.confirm_status='1' "+
                " and b.line_code='" + swStStockReq.getLineCode() + "' "+
                " and b.station_code='" + swStStockReq.getStationCode() + "' "+
                " and (CASE WHEN HOUR(b.WORKING_END_TIME)<2 then DATE_FORMAT(date_sub(b.WORKING_END_TIME,INTERVAL 2 hour),'%Y-%m-%d') else DATE_FORMAT(b.WORKING_END_TIME,'%Y-%m-%d') end)='" + format + "' "+
                " GROUP BY a.TICKET_NAME, a.TICKET_TYPE ";
        List<Map<String, Object>> mapsTicket = JdbcUtil.exeSqlQuery(sqlTicket);
        //调入本站
        String sqlIn = " SELECT SUM(IFNULL(IN_NUMBER,0)) AS num, CARD_TYPE as ticketName, CARD_TYPE_PARAM as ticketType " +
                " FROM sw_st_cycle " +
                " WHERE HANDLE_STATUS = 2 AND DEL_FLAG = 0 " +
                " and IN_LINE_CODE = '" + swStStockReq.getLineCode() + "' " +
                " and IN_STATION_CODE = '" + swStStockReq.getStationCode() + "' " +
                " and DATE_FORMAT(IN_TIME, '%Y-%m-%d' ) = '" + format + "' " +
                " GROUP BY CARD_TYPE, CARD_TYPE_PARAM ";
        List<Map<String, Object>> mapsIn = JdbcUtil.exeSqlQuery(sqlIn);
        //调出本站
        String sqlOut = "SELECT SUM(IFNULL(OUT_NUMBER,0)) AS num, CARD_TYPE as ticketName, CARD_TYPE, CARD_TYPE_PARAM as ticketType " +
                " FROM SW_ST_CYCLE " +
                " WHERE HANDLE_STATUS = 2 AND DEL_FLAG = 0 AND DATE_FORMAT(OUT_TIME, '%Y-%m-%d' )= '" + format + "' " +
                " and OUT_LINE_CODE = '" + swStStockReq.getLineCode() + "' " +
                " and OUT_STATION_CODE = '" + swStStockReq.getStationCode() + "' " +
                " GROUP BY CARD_TYPE, CARD_TYPE_PARAM ";
        List<Map<String, Object>> mapsOut = JdbcUtil.exeSqlQuery(sqlOut);
        //配入本站
        String sqlSave = "SELECT SUM(IFNULL(detail.RECEIVE_COUNT,0)) AS num, detail.TICKET_TYPE as ticketName,detail.TICKET_TYPE_PARAM as ticketType" +
                " FROM sw_tk_ticket_delivery AS delivery LEFT JOIN sw_tk_ticket_delivery_detail AS detail ON delivery.id = detail.REF_ID " +
                " WHERE delivery.DELIVERY_STATUS = 1 " +
                " AND delivery.DEL_FLAG = 0 " +
                " and DATE_FORMAT(delivery.DELIVERY_TIME, '%Y-%m-%d' ) = '" + format + "' " +
                " and delivery.LINE_CODE = '" + swStStockReq.getLineCode() + "' " +
                " and delivery.STATION_CODE = '" + swStStockReq.getStationCode() + "' " +
                " GROUP BY detail.TICKET_TYPE, detail.TICKET_TYPE_PARAM ";
        List<Map<String, Object>> mapsSave = JdbcUtil.exeSqlQuery(sqlSave);
        //上交车票
        String sqlHand = "SELECT SUM(IFNULL(detail.HAND_COUNT,0) ) AS num, detail.TICKET_TYPE as ticketName, detail.TICKET_NAME as ticketType " +
                " FROM sw_st_ticket_hand AS hand LEFT JOIN sw_st_ticket_hand_detail AS detail ON hand.id = detail.REF_ID " +
                " WHERE hand.SUBMIT_STATUS = '1' " +
                " AND hand.DEL_FLAG = '0' " +
                " AND detail.DEL_FLAG = '0' " +
                " and DATE_FORMAT(hand.HAND_TIME, '%Y-%m-%d' ) = '" + format + "' " +
                " and hand.LINE_CODE = '" + swStStockReq.getLineCode() + "' " +
                " and hand.STATION_CODE = '" + swStStockReq.getStationCode() + "' " +
                " GROUP BY detail.TICKET_TYPE, detail.TICKET_NAME ";
        List<Map<String, Object>> mapsHand = JdbcUtil.exeSqlQuery(sqlHand);
        //人工回收
        String sqlRecycle = "SELECT cast(SUM(IFNULL(RECOVER_NUMBER,0)) as SIGNED) AS num, TICKET_TYPE as ticketName, TICKET_NAME as ticketType" +
                " FROM sw_st_recovery " +
                " WHERE DEL_FLAG = 0 " +
                " and DATE_FORMAT(RECOVER_TIME, '%Y-%m-%d' ) = '" + format + "' " +
                " and LINE_CODE = '" + swStStockReq.getLineCode() + "' " +
                " and STATION_CODE = '" + swStStockReq.getStationCode() + "' " +
                " GROUP BY TICKET_TYPE, TICKET_NAME ";
        List<Map<String, Object>> mapsRecycle = JdbcUtil.exeSqlQuery(sqlRecycle);

		//车票替换  20231227
		String sqlTicketReplace = "SELECT count(*) AS num, TICKET_TYPE as ticketName, TICKET_NAME as ticketType" +
                " FROM sw_st_input_passenger_work_ticket " +
                " WHERE DEL_FLAG = 0 and OPERATION_TYPE= 0 and HANDLE_TYPE= 1 and INVALID_STATUS=0 "+
			    " and TICKET_NAME in (select b.SUB_EN_NAME from sys_dict_item a,sw_pm_ticket_card_type_param b where a.label=b.SUB_NAME and  a.type='bom_small_ticket_type' and a.description='2') " +
                " and DATE_FORMAT(HANDLE_TIME, '%Y-%m-%d' ) = '" + format + "' " +
                " and LINE_CODE = '" + swStStockReq.getLineCode() + "' " +
                " and STATION_CODE = '" + swStStockReq.getStationCode() + "' " +
                " GROUP BY TICKET_TYPE, TICKET_NAME ";
        List<Map<String, Object>> mapsTicketReplace = JdbcUtil.exeSqlQuery(sqlTicketReplace);

        for(SwStStock swStStockCo : collection){
            SwStStock swStStock = new SwStStock();
            //BeanUtils.copyProperties(swStStockReq,swStStock);
            swStStock.setLineCode(swStStockReq.getLineCode());
            swStStock.setStationCode(swStStockReq.getStationCode());
            swStStock.setStatisticsDate(swStStockReq.getStatisticsDate());
            swStStock.setCreatorJobNo(swStStockReq.getCreatorJobNo());
            //设置初始值为0
            swStStock.setTransferStation(0);
            swStStock.setDistributionStation(0);
            swStStock.setAgmRecovery(0);
            swStStock.setArtificialRecovery(0);
            swStStock.setBoxOfficeSale(0);
			swStStock.setTicketReplace(0);
            swStStock.setTvmSellOut(0);
            swStStock.setInternetSales(0);
            swStStock.setLeaveStation(0);
            swStStock.setHandTicket(0);
            swStStock.setTvmScrapTicket(0);
            swStStock.setBomScrapTicket(0);
            swStStock.setAgmScrapTicket(0);
            swStStock.setNetworkScrapTicket(0);
            swStStock.setScrapSubtotal(0);
            swStStock.setTicketTypeEn(swStStockCo.getTicketTypeEn());
            swStStock.setTicketTypeParamEn(swStStockCo.getTicketTypeParamEn());
            swStStock.setConfirmStatus("0");
            swStStock.setDelFlag("0");
            //上日结存=上一天的本日结存
            swStStock.setBalanceLastday(swStStockCo.getBalanceToday());
            String ticketType = swStStockCo.getTicketTypeEn();
            String ticketName = swStStockCo.getTicketTypeParamEn();

            if("PTDCP".equals(swStStockCo.getTicketTypeParamEn())){
                swStStock.setAgmRecovery(agmRecovery);
                swStStock.setTvmSellOut(tvmSellOut);
                swStStock.setBoxOfficeSale(boxOfficeSale);
                swStStock.setInternetSales(internetSales);
				 //LOGGER.info("库存盘点查询结果=PTDCP==="+tvmScrap+","+bomScrap+","+agmScrap+","+netScrap);
			    if(null != mapsCheck && 0 != mapsCheck.size()){ //有盘点数据时加上废票的数据,本日结存公式不影响
					swStStock.setBomScrapTicket(bomScrap);
					swStStock.setTvmScrapTicket(tvmScrap);
					swStStock.setAgmScrapTicket(agmScrap);
					swStStock.setNetworkScrapTicket(netScrap);
                    swStStock.setScrapSubtotal(bomScrap+tvmScrap+agmScrap+netScrap);	
					 //LOGGER.info("库存盘点查询结果=setScrapSubtotal==="+tvmScrap+","+bomScrap+","+agmScrap+","+netScrap);
				}
            }else{
                //非单程票的时候获取票房售出 --减去车票替换
                //swStStock.setBoxOfficeSale(getIntValue(mapsTicket,ticketName,ticketType)-getIntValue(mapsTicketReplace,ticketName,ticketType));
                int boxsale=getIntValue(mapsTicket,ticketName,ticketType)-getIntValue(mapsTicketReplace,ticketName,ticketType);
                //LOGGER.info("票房售出数量"+getIntValue(mapsTicket,ticketName,ticketType)+"；即时替换票数量"+getIntValue(mapsTicketReplace,ticketName,ticketType)+"实际票房售出数量"+boxsale);
                swStStock.setBoxOfficeSale(boxsale);
                swStStock.setTicketReplace(getIntValue(mapsTicketReplace,ticketName,ticketType));//增加车票替换的设置 20231227
            }
            //调入本站
            swStStock.setTransferStation(getIntValue(mapsIn,ticketName,ticketType));

            //调出本站
            swStStock.setLeaveStation(getIntValue(mapsOut,ticketName,ticketType));

            //配入本站
            swStStock.setDistributionStation(getIntValue(mapsSave,ticketName,ticketType));

            //上交车票
            swStStock.setHandTicket(getIntValue(mapsHand,ticketName,ticketType));

            //人工回收
            swStStock.setArtificialRecovery(getIntValue(mapsRecycle,ticketName,ticketType));

            //本日结存=上日结存+调入本站+配入本站+AGM回收+AGM废票+人工回收-票房售出-车票替换- TVM售出-网络售出-调出本站-上交车票
            swStStock.setBalanceToday(swStStock.getBalanceLastday() + swStStock.getTransferStation() + swStStock.getDistributionStation() + swStStock.getAgmRecovery() +swStStock.getAgmScrapTicket() + swStStock.getArtificialRecovery()
                        - swStStock.getBoxOfficeSale()  - swStStock.getTicketReplace() - swStStock.getTvmSellOut() - swStStock.getInternetSales() - swStStock.getLeaveStation() - swStStock.getHandTicket());
            
			if(swStStock.getTicketReplace()!=0){
			  swStStock.setRemark("车票替换"+swStStock.getTicketReplace()+"张");
			}
            list.add(swStStock);
        }
        if(null == list || 0 == list.size()){
            return false;
        }
        this.saveOrUpdateBatch(list);
        return true;
    }

    @SneakyThrows
    @Override
    public boolean saveBatch(Collection<SwStStock> entityList) {
        List swSwStockList = new ArrayList();
        if(entityList.size()>0){
            for(SwStStock swStStock : entityList){
                List<Map<String, Object>> maps = JdbcUtil.exeSqlQuery("SELECT SUB_EN_NAME,MAIN_EN_NAME FROM SW_PM_TICKET_CARD_TYPE_PARAM WHERE SUB_NAME='" + swStStock.getTicketTypeParamEn() + "'");
                swStStock.setTicketTypeEn(String.valueOf(maps.get(0).get("MAIN_EN_NAME")));
                swStStock.setTicketTypeParamEn(String.valueOf(maps.get(0).get("SUB_EN_NAME")));
                Map req = new HashMap<>();
                req.put("ticketTypeEn",swStStock.getTicketTypeEn());
                req.put("ticketTypeParamEn",swStStock.getTicketTypeParamEn());
                SimpleDateFormat dff = new SimpleDateFormat("yyyy-MM-dd");
                String format = dff.format(swStStock.getStatisticsDate());
                req.put("statisticsDate",format);
                req.put("lineCode",swStStock.getLineCode());
                req.put("stationCode",swStStock.getStationCode());
                req.put("delFlag","0");
                List<SwStStock> swStStockByParam = swStStockMapper.getSwStStockByParam(req);
                SwStStock swStStockM = new SwStStock();
                if(null != swStStockByParam && 0 != swStStockByParam.size()){
                    Integer id = swStStockByParam.get(0).getId();
                    BeanUtils.copyProperties(swStStock,swStStockM);
                    swStStockM.setId(id);
                }else{
                    swStStockM = swStStock;
                }
                swStStockM.setConfirmStatus("0");
                swSwStockList.add(swStStockM);
            }
            this.saveOrUpdateBatch(swSwStockList);
        }
        return false;
    }

    private int getIntValue( List<Map<String,Object>> listMap,String ticketName,String ticketType) {
        if(listMap == null || listMap.isEmpty()) {
            return 0;
        }
        for (Map<String,Object> map : listMap){
            String ticketNameInit = String.valueOf(map.get("ticketName"));
            String ticketTypeInit = String.valueOf(map.get("ticketType"));
            if(ticketNameInit.equals(ticketType) && ticketTypeInit.equals(ticketName)) {
                return Integer.valueOf(String.valueOf(map.get("num")));
            }
        }
        return 0;
    }

    /**
     * 导出车站车票库存日报表
     * @param swStStock
     * @param response
     */
    @Override
    public void export(SwStStock swStStock, HttpServletResponse response) throws SQLException {
        String sqlTicket = "select main_en_name AS mainEnName, main_name AS mainName, sub_en_name AS subEnName, sub_name AS subName " +
                "from SW_PM_TICKET_CARD_TYPE_PARAM  WHERE DEL_FLAG='0' order by main_en_name,sub_en_name";
        List<Map<String, Object>> mapsTicket = JdbcUtil.exeSqlQuery(sqlTicket);
        List<SwStStock> swStStockList = swStStockMapper.selectList(Wrappers.lambdaQuery(swStStock));
        swStStockList.forEach(x -> {
            Map<String, Object> ticketType = getTicketValue(mapsTicket, x.getTicketTypeEn(), x.getTicketTypeParamEn());
            if(ObjectUtil.isEmpty(ticketType)){
                throw new RuntimeException("错误！");
            }
            x.setTicketTypeEn(String.valueOf(ticketType.get("mainName")));//票种
            x.setTicketTypeParamEn(String.valueOf(ticketType.get("subName")));//车票名称
        });

        InputStream excelTemplateIs = null;
        try {

            response.reset(); // 非常重要
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            final String fileName = URLEncoder.encode("车站车票库存日报表", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + System.currentTimeMillis() + ".xlsx");

            // 模板注意 用{} 来表示你要用的变量 如果本来就有"{","}" 特殊字符 用"\{","\}"代替
            // {} 代表普通变量 {.} 代表是list的变量

            excelTemplateIs = this.getClass().getResourceAsStream("/static/excel/template/SwStStockExcelTemplate.xlsx");

            ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).registerConverter(new LocalDateTimeConverter()).registerConverter(new LocalDateConverter()).withTemplate(excelTemplateIs).build();
            WriteSheet writeSheet = EasyExcel.writerSheet("车站车票库存日报表").build();
            // 这里注意 入参用了forceNewRow 代表在写入list的时候不管list下面有没有空行 都会创建一行，然后下面的数据往后移动。默认 是false，会直接使用下一行，如果没有则创建。
            // forceNewRow 如果设置了true,有个缺点 就是他会把所有的数据都放到内存了，所以慎用
            // 简单的说 如果你的模板有list,且list不是最后一行，下面还有数据需要填充 就必须设置 forceNewRow=true 但是这个就会把所有数据放到内存 会很耗内存
            // 如果数据量大 list不是最后一行 参照另一个
            FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
            excelWriter.fill(swStStockList, fillConfig, writeSheet);

            Map<String, Object> map = new HashMap<>();
            String lineCode = SecurityUtils.getUser().getLineCode();
            String stationCode = SecurityUtils.getUser().getStationCode();
            String lineName = "";
            String stationName= "";
            List lst = getLineNameStationName(lineCode,stationCode);
            if(lst!=null && lst.size()>0){
                lineName  = String.valueOf(lst.get(0));
                stationName  = String.valueOf(lst.get(1));

            }
            map.put("statisticsDate", DateUtilStm.dateToString(swStStock.getStatisticsDate(),"yyyy-MM-dd"));
            map.put("lineName", lineName);
            map.put("stationName", stationName);
            excelWriter.fill(map, writeSheet);

            excelWriter.finish();

        } catch (Exception e) {
            e.printStackTrace();
            log.error("导出车站车票库存日报表错误");
        } finally {
            if(excelTemplateIs != null){
                try {
                    excelTemplateIs.close();
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                }

            }
        }
    }

    @Override
    public String getCheckDay() {
        return swStStockMapper.getCheckDay();
    }

    private List getLineNameStationName(String lineCode,String stationCode){
        List lst = new ArrayList();
        try{

            String sql = "select a.name as linename,b.name as stationname from sw_param_line a,sw_param_station b where a.code=b.line_code  and a.del_flag='0' and b.del_flag='0' and a.code='"+lineCode+"' and b.code='"+stationCode+"' ";
            List<Map<String,Object>> lstMap =  JdbcUtil.exeSqlQueryByCon(sql);
            if(lstMap!=null && lstMap.size()>0){
                lst.add((String)lstMap.get(0).get("linename"));
                lst.add((String)lstMap.get(0).get("stationname"));
            }
        }catch(Exception e){

        }
        return lst;
    }

    private Map<String,Object> getTicketValue( List<Map<String,Object>> listMap,String mainEnName,String subEnName) {
        if(listMap == null || listMap.isEmpty()) {
            return null;
        }
        for (Map<String,Object> map : listMap){
            String mainEnNameInit = String.valueOf(map.get("mainEnName"));
            String subEnNameInit = String.valueOf(map.get("subEnName"));
            if(mainEnNameInit.equals(mainEnName) && subEnNameInit.equals(subEnName)) {
                return map;
            }
        }
        return null;
    }

	@Override
    public List<Map<String, Object>> getCheckScrapTicket(String lineCode,String stationCode,String statisticsDateStr){

	  try{
	    	
			String sql ="select a.real_check_number as CHECK_NUMBER,a.ticket_type as TICKET_TYPE from sw_st_ticket_check_oneway a where a.ticket_type in('5','6','7','8') and a.del_flag='0' and  a.relation_id =(select id from sw_st_ticket_check b where  b. del_flag='0' and b.status in ('0','1','2') and DATE_FORMAT(b.CHECK_TIME,'%Y%m%d') = '"+statisticsDateStr+"' and b.line_code='"+lineCode+"' and b.station_code='"+stationCode+"'   order by b.create_time desc limit 0,1)";
			 //LOGGER.info("库存SQL==="+sql);
			return  JdbcUtil.exeSqlQuery(sql);
 		
		}catch(Exception e){
			  return null;
		}	
		
	}
}
